//
//  BGHomeTableViewController.m
//  bigMall
//
//  Created by ios on 16/7/6.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGHomeTableViewController.h"
#import "BGDateResult.h"
#import "BGParam.h"
#import "UIView+FrameExtension.h"
#import "BGHomeTableViewCell.h"
#import <CoreLocation/CoreLocation.h>
#import "BGLoginMode.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "BGShopDataModel.h"
#import "BGEntrustViewController.h"
#import "BGFaBuViewController.h"
#import "BGAddInviteOneTableViewController.h"
#import "BGBasicUrl.h"
#import "BGAdvertisingController.h"
#import "BGImagesListModel.h"
#import "BGMoreMessageCell.h"
#import "BGTenderTableViewController.h"
#import "BGShopTableViewControler.h"
#import "BGTenderAndAuctionCell.h"
#import "BGTenderAuctionModel.h"
#import "BGShopCellModel.h"
#import "BGShopTableViewCell.h"
#import "BGGoodInfoViewController.h"
#import "BGShopCellModel.h"
#import "BGTenderInfoViewController.h"
#import "GetCurrentDeviceModel.h"
#import "BGInformationController.h"
#import "BGShoppingViewController.h"
#import "BGBrandZoneViewController.h"
#import "BGIdeaViewController.h"
#import "JYCarousel.h"
#import "BGPublicAnnoucementViewController.h"
#import "BGBrandZoneViewController.h"
#import "BGHomeWebViewController.h"

#define BGHeight self.view.bounds.size.height
#define BGWidth self.view.bounds.size.width
//#define pageCount _iamgeArrM.count
static NSUInteger pageCount;
@interface BGHomeTableViewController () <CLLocationManagerDelegate>{
    
    UIScrollView *_scrollView;//滚动图
    NSTimer *_timer;//定时器
    UIPageControl * _PageCtr;//指示器
    CGFloat _oldY;
    UIView *a;
    UILabel *_lab;//显示的标签
    CLLocationManager *_manager;//定位器的管理者
    NSArray *_dataArr;
    UIView *view;//定位小视图
    
    NSMutableArray* _iamgeArrM;
    UIImageView *imageView;
    
    NSArray *OneCelldateArray;
    NSArray *TwoCelldateArray;
    NSArray *oneSoureArray;
    NSArray *twoSoureArray;
    
    CGFloat font;//根据版本号判断字体大小的
    
    NSMutableArray *imageArr;
    
}

@end

@implementation BGHomeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
    back.title = @"";
    self.navigationItem.backBarButtonItem = back;
    [self.navigationItem.backBarButtonItem setTintColor:[UIColor whiteColor]];
    
    GetCurrentDeviceModel *model = [[GetCurrentDeviceModel alloc] init];
    NSString *currentDevice = [model getCurrentDeviceModel];
    if ([currentDevice isEqualToString:@"iPhone5"] || [currentDevice isEqualToString:@"iPhone5"]||[currentDevice isEqualToString:@"iPhone5s"]||[currentDevice isEqualToString:@"iPhone5c"]||[currentDevice isEqualToString:@"iPhoneSE"]) {
        font = 8;
        [self.tableView reloadData];
    } else if ([currentDevice isEqualToString:@"iPhone6"] || [currentDevice isEqualToString:@"iPhone6s"]||[currentDevice isEqualToString:@"iPhone7"]) {
        font = 9;
        [self.tableView reloadData];
    } else if ([currentDevice isEqualToString:@"iPhone7Plus"] || [currentDevice isEqualToString:@"iPhone6Plus"]||[currentDevice isEqualToString:@"iPhone6sPlus"]){
        font = 12;
        [self.tableView reloadData];
    } else if ([currentDevice isEqualToString:@"iPhoneSimulator"]){
        font = 9;
    }
    
    //网络的请求
    [self loadInter];
    
    //设置导航栏左边的定位
    [self setCoreLocation];
    
    //去掉没必要的线
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(index)];
    [self.tableView.header beginRefreshing];
    
//    [BGDateResult loadShopHomeDataWithCatId:@"6" province:@"1" order:@"price" thisPage:@"1" pageNum:@"10" success:^(NSObject *resultData) {
//        
//        BGShopDataModel *model = (BGShopDataModel *)resultData;
//        NSLog(@"%@",model.keyValues);
//    } failure:^(NSError *error) {
//        
//        
//        
//    }];
    
    
}
- (void)index {
//    [self loadInter];
    [self loadOneData];
    [self loadTwoData];
}
- (void)loadInter {
    
    [BGDateResult imagesListWithType:@"indexBanner" thisPage:@"1" pageNum:@"10" success:^(NSObject *result) {
        
        BGImagesListModel *model = (BGImagesListModel *)result;
        
        _iamgeArrM = [NSMutableArray arrayWithArray:model.res];
        
        pageCount = 4;
        imageArr = [NSMutableArray array];
        for (int i = 1; i <= _iamgeArrM.count; i++) {
             BGImagesListModelList *model = _iamgeArrM[i - 1];
            [imageArr addObject:[NSString stringWithFormat:@"%@%@",[BGBasicUrl getBasicUrl],model.path]];
        }
        //创建了界面
        [self createUI];

    [self.tableView.header endRefreshing];
        
    } failure:^(NSError *error) {
        
    }];
    
//    [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",[BGBasicUrl getBasicUrl],model.imgsrc]]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideNo:) name:@"netWorkStatus" object:nil];
    
}
- (void)hideNo:(NSNotification *)nofication {
    
    if ([[nofication.userInfo objectForKey:@"key"] isEqualToString:@"0"]) {
        self.tableView.tableHeaderView.hidden = YES;
        a.hidden = YES;
    } else {
        self.tableView.tableHeaderView.hidden = NO;
        a.hidden = NO;
    }

//    self.tableView.
    
}
- (void)createUI {
    
    __weak typeof(self) weakSelf = self;
    JYCarousel *carouselView = [[JYCarousel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width / 3) configBlock:^JYConfiguration *(JYConfiguration *carouselConfig) {
        //配置指示器类型
        carouselConfig.pageContollType = MiddlePageControl;
        //配置轮播时间间隔
        carouselConfig.interValTime = 2.5;
        //配置轮播翻页动画
        carouselConfig.pushAnimationType = PushFade;
        //配置动画方向
        carouselConfig.animationSubtype = kCATransitionFromRight;
        
        //        carouselConfig.backViewColor = [UIColor purpleColor];
        
        carouselConfig.contentMode = UIViewContentModeScaleToFill;
        
        carouselConfig.pageTintColor = [UIColor whiteColor];
        
        carouselConfig.currentPageTintColor = [UIColor orangeColor];
        
        return carouselConfig;
    } clickBlock:^(NSInteger index) {
        //点击imageView回调方法
        [weakSelf clickIndex:index];
    }];
    //开始轮播
    [carouselView startCarouselWithArray:imageArr];

    self.tableView.tableHeaderView = carouselView;
    
}
- (void)clickIndex:(NSInteger)index {
    
}
- (void)setCoreLocation {
    
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 90, 30)];
//    view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *leftVie = [[UIBarButtonItem alloc] initWithCustomView:view];
    
    //小图标
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 3, 21, 21)];
    
    image.image = [UIImage imageNamed:@"图层-26"];
    image.contentMode = UIViewContentModeScaleAspectFit;
    
    [view addSubview:image];
    
    //显示地理的位置
    _lab = [[UILabel alloc] initWithFrame:CGRectMake(25, 3, 61, 21)];
    _lab.font = [UIFont systemFontOfSize:16];
    _lab.textColor = [UIColor whiteColor];
//    _lab.backgroundColor = [UIColor blueColor];
    
    [view addSubview:_lab];
    
    self.navigationItem.leftBarButtonItem  = leftVie;
    
    //定位的操作
    if ([CLLocationManager locationServicesEnabled] == NO || [CLLocationManager headingAvailable] == NO) {
        GWLog(@"定位设备不可用");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"定位不成功，请确认开启定位" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        
        [alert show];
        
        //程序返回
        return;
    }
        //初始化定位管理者对象
        _manager = [[CLLocationManager alloc] init];
        
        //做定位的相关操作（设置）
        
        //设置精度
        /*
         kCLLocationAccuracyBest;              最高精度
         kCLLocationAccuracyNearestTenMeters;  10米精度
         kCLLocationAccuracyHundredMeters;     100米精度
         kCLLocationAccuracyKilometer;         1千米精度
         kCLLocationAccuracyThreeKilometers;   3千米精度
         设置精度时根据实际情况而定，如果精度越高，手机耗电量越大
         */
        _manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        //设置定位的距离筛选器 ，此属性的作用是当前位置方式改变时，其移动的距离超过了筛选值，就会触发协议中的方法
        //这里设置单位是米  （1米） double类型
        _manager.distanceFilter = 1;
        //设置代理
        _manager.delegate = self;
        
        /*
         设置手机的当前方法
         了解
         CLDeviceOrientationUnknown = 0,    没有
         CLDeviceOrientationPortrait,       肖像
         CLDeviceOrientationPortraitUpsideDown, 肖像倒过来
         CLDeviceOrientationLandscapeLeft,    向左
         CLDeviceOrientationLandscapeRight,   向右
         CLDeviceOrientationFaceUp,           面向上
         CLDeviceOrientationFaceDown          面向下
         
         */
        _manager.headingOrientation = CLDeviceOrientationPortrait;
        
        //请求用户授权，自从iOS8.0开始需要手动请求用户授权
        //取到当前设备的版本号 如果大于8.0就手动开启提示
        if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
            //此方法请求的授权，仅限于用户在打开使用APP时允许使用系统的定位服务（在应用使用期间）
            [_manager requestWhenInUseAuthorization];
            //请求的授权，除了可以在APP打开时允许定位服务，也可以在APP进入后台仍然可以使用定位服务 （永久）
            //                [_locationManager requestAlwaysAuthorization];
        }
        
    
    
    [_manager startUpdatingLocation];
    
}

#pragma mark - 实现定位协议回调方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *currentLocation = [locations lastObject];
    
    //获取当前城市的地名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //反向的地理编码
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count > 0)
            
        {
            
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            
            //将获得的所有信息显示到label上
            
            _lab.text = placemark.name;
            
            //获取城市
            
            NSString *city = placemark.locality;
            
            if (!city) {
                
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                
                city = placemark.administrativeArea;
                
            }
            
            _lab.text = city;
            
        }
        
        else if (error == nil && [placemarks count] == 0)
            
        {
            
            GWLog(@"No results were returned.");
            
        }
        
        else if (error != nil)
            
        {
            
            GWLog(@"An error occurred = %@", error);
            
        }
        
    }];
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    
    [manager stopUpdatingLocation];
    
}

- (void)locationManager:(CLLocationManager *)manager

       didFailWithError:(NSError *)error {
    
    if (error.code == kCLErrorDenied) {
        
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of aresources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return OneCelldateArray.count + 1;
    }else
        return TwoCelldateArray.count + 1;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return 34;
    }else {
    
    return 108;
    
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            BGShopTableViewControler *adc = [[BGShopTableViewControler alloc] init];
            adc.title = @"商城";
            adc.isHome = @"q";
            self.tabBarController.selectedIndex = 1;
//            [self.navigationController pushViewController:adc animated:YES];
        }else {
            
            //1
//            BGTenderAuctionModel *model = OneCelldateArray[indexPath.row -1];
            BGShopCellModel *model = oneSoureArray[indexPath.row -1];
            BGGoodInfoViewController *vc = [BGGoodInfoViewController new];
            vc.goodId = model.id;
            
            [self.navigationController pushViewController:vc animated:YES];
            
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            BGTenderTableViewController *adc = [[BGTenderTableViewController alloc] init];
            adc.title = @"招标";
            self.tabBarController.selectedIndex = 2;
            adc.isHome = @"q";
//            [self.navigationController pushViewController:adc animated:YES];
        } else {
            
            //2
            BGShopCellModel *model = twoSoureArray[indexPath.row -1];
            BGTenderInfoViewController *vc = [BGTenderInfoViewController new];
            vc.goodId = model.id;
            
            [self.navigationController pushViewController:vc animated:YES];
            
        }
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        [tableView registerClass:[BGMoreMessageCell class] forCellReuseIdentifier:@"celId1"];
        
        BGMoreMessageCell *cel = [tableView dequeueReusableCellWithIdentifier:@"celId1" forIndexPath:indexPath];
        
        if (indexPath.section == 0) {
            cel.labText = @"供应信息";
        } else {
            cel.labText = @"采购信息";
        }
        
//        cel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        return cel;
    }else {
        if (indexPath.section == 0 ) {
            BGTenderAndAuctionCell *cell = [BGTenderAndAuctionCell cellWithTableView:tableView];
            BGTenderAuctionModel *model = OneCelldateArray[indexPath.row -1];
            cell.model = model;
            
//            BGShopTableViewCell *cell = [BGShopTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
//            cell.model = OneCelldateArray[indexPath.row - 1];
            
            return cell;
        }else if(TwoCelldateArray.count > 0){
            
            BGTenderAndAuctionCell *cell = [BGTenderAndAuctionCell cellWithTableView:tableView];
            BGTenderAuctionModel *model = TwoCelldateArray[indexPath.row -1];
            cell.model = model;
            return cell;
        }else
            return nil;
        
    
    }
    
}
- (instancetype)init
{
    if (self = [super init]) {
        [self loadOneData];
        [self loadTwoData];
    }
    return self;
}


- (void)loadOneData
    {
        //    if (!_dataArray.count) {
        //        _thisPage = 1;
        //    }
        [BGDateResult loadShopHomeDataWithCatId:@"" province:@"" order:@"" thisPage:@"1" pageNum:@"3" success:^(NSObject *resultData) {
            //        [self.tableView mj_header];
            
            
            BGShopDataModel *model = (BGShopDataModel *)resultData;
            //                NSLog(@"%@",model.keyValues);
//            if ([model.allPage integerValue] > [_pageNum integerValue]) {
//                self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
//            }
//            
//            _dataArray =(NSMutableArray *) model.list;
            OneCelldateArray = [[NSMutableArray alloc]initWithArray:[self getModelWithBGShopModel:model.list]];
            oneSoureArray = model.list;
//            _thisPage = 2;
//            _allPage = [model.allPage integerValue];
//            //        _thisPage ++;
            [self.tableView.header endRefreshing];
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            
            
        }];
    }

- (void)loadTwoData
{
    //    if (!_dataArray.count) {
    //        _thisPage = 1;
    //    }
    [BGDateResult inviteListWithThisPage:@"1" catId:@"" provience:@"" order:@"id" pageNum:@"3" success:^(NSObject *result) {
        BGShopDataModel *model = (BGShopDataModel *)result;
//        [self.tableView.header endRefreshing];
//        TwoCelldateArray = model.list;
        TwoCelldateArray = [[NSMutableArray alloc]initWithArray:[self getModelWithBGShopModel:model.list]];
//        OneCelldateArray =  [[NSMutableArray alloc]initWithArray:[self getModelWithBGShopModel:model.list]];
        twoSoureArray = model.list;
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
//        if ([model.allPage integerValue] > [_pageNum integerValue]) {
//            self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
//            _thisPage = 2;
//            _allPage = [model.allPage integerValue];
//        }
    } failure:^(NSError *errot) {
        
    }];
    

}

- (NSArray *)getModelWithBGShopModel:(NSArray *)array
{
    NSMutableArray *dataArray = [NSMutableArray array];
    for (BGShopCellModel *model in array) {
        
        BGTenderAuctionModel *TAModel = [[BGTenderAuctionModel alloc ]init];
        TAModel.title = model.title;
        TAModel.iScaiFen = [model.caiFen isEqualToString:@"是"];
        TAModel.time = model.add_time;
        NSString *price = [NSString stringWithFormat:@"报盘价:%@元/%@",model.priceNow,model.unit];
        TAModel.price = price;
        TAModel.Num = [NSString stringWithFormat:@"库存%@%@",model.kuCun,model.unit];
        TAModel.imageOne = @"add.png";
        TAModel.Add = [NSString stringWithFormat:@"交货地:%@",model.addr];
        TAModel.imageTwo = @"接收.png";
        TAModel.jiaoHuoFangShi = [NSString stringWithFormat:@"交货方式:%@",model.jiaoHuoFangShi];
        TAModel.guaDanFangShi = model.GuaDanFangShi;
        [dataArray addObject:TAModel];
    }
    
    return dataArray;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
      return (BGHeight - 108) / 6 * 2.21;
    } else {
        return 0;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
    a = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BGWidth, (BGHeight - 108) / 6 + 21)];
    
    a.backgroundColor = [UIColor whiteColor];
    
    for (int i = 1; i <= 4; i++) {
        
        if (i == 1) {
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake( BGWidth / 16, 10, BGWidth / 10, BGWidth /10 )];
            btn.tag = 10 + i;
//            btn.backgroundColor = [UIColor blackColor];
            btn.clipsToBounds = YES;
            btn.layer.cornerRadius = BGWidth / 16;
            [btn setImage:[UIImage imageNamed:@"公告"] forState:UIControlStateNormal];
            [btn setContentMode:UIViewContentModeScaleToFill];
            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            btn.imageView.contentMode = UIViewContentModeScaleAspectFill;
            [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
            [a addSubview:btn];
            
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake( BGWidth / 16, btn.bottom, BGWidth / 10,  10 )];
            lab.text = @"公告信息";
            lab.textAlignment = NSTextAlignmentCenter;
            [lab setTextColor:[UIColor blackColor]];
            lab.font = [UIFont systemFontOfSize:font];
            [a addSubview:lab];
            
        } else if (i == 2){
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(5 * BGWidth / 16, 10, BGWidth / 10, BGWidth / 10)];
            btn.tag = 10 + i;
            [btn setContentMode:UIViewContentModeScaleToFill];
//            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
//            btn.backgroundColor = [UIColor blackColor];
            [btn setImage:[UIImage imageNamed:@"委托"] forState:UIControlStateNormal];
            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            btn.clipsToBounds = YES;
            btn.layer.cornerRadius = BGWidth / 16;
            [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
            [a addSubview:btn];
            
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(5 * BGWidth / 16, btn.bottom, BGWidth / 10,  10)];
            lab.text = @"委托业务";
            lab.font = [UIFont systemFontOfSize:font];
            lab.textAlignment = NSTextAlignmentCenter;
            [a addSubview:lab];
            
        } else if (i == 3) {
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(9 * BGWidth / 16, 10, BGWidth / 10, BGWidth / 10)];
            btn.tag = 10 + i;
            [btn setContentMode:UIViewContentModeScaleToFill];
//            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
//            btn.backgroundColor = [UIColor blackColor];
            [btn setImage:[UIImage imageNamed:@"购物"] forState:UIControlStateNormal];
            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            btn.clipsToBounds = YES;
            btn.layer.cornerRadius = BGWidth / 16;
            [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
            [a addSubview:btn];
            
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(9 * BGWidth / 16, btn.bottom, BGWidth / 10,10)];
            lab.text = @"发布商品";
            lab.font = [UIFont systemFontOfSize:font];
            lab.textAlignment = NSTextAlignmentCenter;
            [a addSubview:lab];
            
        } else if (i == 4) {
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(13 * BGWidth / 16, 10, BGWidth / 10, BGWidth / 10)];
            btn.tag = 10 + i;
            [btn setContentMode:UIViewContentModeScaleToFill];
//            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
//            btn.backgroundColor = [UIColor blackColor];
            [btn setImage:[UIImage imageNamed:@"书"] forState:UIControlStateNormal];
            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            btn.clipsToBounds = YES;
            btn.layer.cornerRadius = BGWidth / 16;
            [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
            [a addSubview:btn];
            [btn setContentMode:UIViewContentModeScaleToFill];
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(13 * BGWidth / 16, btn.bottom, BGWidth / 10,  10)];
            lab.text = @"发布招标";
            lab.font = [UIFont systemFontOfSize:font];
            lab.textAlignment = NSTextAlignmentCenter;
            
            [a addSubview:lab];
            
        }
        
    }
    for (int i = 1; i <= 4; i++) {
        
        if (i == 1) {
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake( BGWidth / 16, BGWidth / 10 + 16 + BGWidth /16, BGWidth / 10, BGWidth /10 )];
            btn.tag = 30 + i;
//            btn.backgroundColor = [UIColor blackColor];
            [btn setImage:[UIImage imageNamed:@"书"] forState:UIControlStateNormal];
            btn.clipsToBounds = YES;
            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            btn.layer.cornerRadius = BGWidth / 16;
            [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
            [a addSubview:btn];
            [btn setContentMode:UIViewContentModeScaleToFill];
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake( BGWidth / 16, btn.bottom, BGWidth / 10, 10 )];
            lab.text = @"热门资讯";
            lab.textAlignment = NSTextAlignmentCenter;
            [lab setTextColor:[UIColor blackColor]];
            lab.font = [UIFont systemFontOfSize:font];
            [a addSubview:lab];
            
        } else if (i == 2){
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(5 * BGWidth / 16, BGWidth / 10 + 16 + BGWidth /16, BGWidth / 10, BGWidth / 10)];
            btn.tag = 30 + i;
           [btn setContentMode:UIViewContentModeScaleToFill];
//            btn.backgroundColor = [UIColor blackColor];
            [btn setImage:[UIImage imageNamed:@"icon_A bulk"] forState:
             UIControlStateNormal];
            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            btn.clipsToBounds = YES;
            btn.layer.cornerRadius = BGWidth / 16;
            [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
            [a addSubview:btn];
            
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(5 * BGWidth / 16, btn.bottom, BGWidth / 10,  10)];
            lab.text = @"团购";
            lab.font = [UIFont systemFontOfSize:font];
            lab.textAlignment = NSTextAlignmentCenter;
            [a addSubview:lab];
            
        } else if (i == 3) {
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(9 * BGWidth / 16, BGWidth / 10 + 16 + BGWidth /16, BGWidth / 10, BGWidth / 10)];
            [btn setContentMode:UIViewContentModeScaleToFill];
            btn.tag = 30 + i;
//            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
//            btn.backgroundColor = [UIColor blackColor];
            [btn setImage:[UIImage imageNamed:@"icon_Brand zone"] forState:UIControlStateNormal];
            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            btn.clipsToBounds = YES;
            btn.layer.cornerRadius = BGWidth / 16;
            [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
            [a addSubview:btn];
            
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(9 * BGWidth / 16, btn.bottom, BGWidth / 10, 10)];
            lab.text = @"品牌专区";
            lab.font = [UIFont systemFontOfSize:font];
            lab.textAlignment = NSTextAlignmentCenter;
            [a addSubview:lab];
            
        } else if (i == 4) {
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(13 * BGWidth / 16, BGWidth / 10 + 16 + BGWidth /16, BGWidth / 10, BGWidth / 10)];
            btn.tag = 30 + i;
//            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
//            btn.backgroundColor = [UIColor blackColor];
            [btn setImage:[UIImage imageNamed:@"汇报"] forState:UIControlStateNormal];
            btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            btn.clipsToBounds = YES;
            btn.layer.cornerRadius = BGWidth / 16;
            [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
            [a addSubview:btn];
            [btn setContentMode:UIViewContentModeScaleToFill];
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(13 * BGWidth / 16, btn.bottom, BGWidth / 10,  10)];
            lab.text = @"慧煤帮助";
            lab.font = [UIFont systemFontOfSize:font];
            lab.textAlignment = NSTextAlignmentCenter;
            
            [a addSubview:lab];
            
        }
        
    }
        
        //第三层视图
        for (int i = 1; i <= 4; i++) {
            
            if (i == 1) {
                
                UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake( BGWidth / 16, BGWidth / 10 + 16 + BGWidth /16 + BGWidth /10 + BGWidth /16 + 6, BGWidth / 10, BGWidth /10 )];
                btn.tag = 20 + i;
                //            btn.backgroundColor = [UIColor blackColor];
                [btn setImage:[UIImage imageNamed:@"icon_logistics"] forState:UIControlStateNormal];
                btn.clipsToBounds = YES;
                btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
                btn.layer.cornerRadius = BGWidth / 16;
                [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
                [a addSubview:btn];
                [btn setContentMode:UIViewContentModeScaleToFill];
                UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake( BGWidth / 16, btn.bottom, BGWidth / 10, 10 )];
                lab.text = @"物流";
                lab.textAlignment = NSTextAlignmentCenter;
                [lab setTextColor:[UIColor blackColor]];
                lab.font = [UIFont systemFontOfSize:font];
                [a addSubview:lab];
                
            } else if (i == 2){
                
                UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(5 * BGWidth / 16, BGWidth / 10 + 16 + BGWidth /16 + BGWidth /10 + BGWidth /16 + 6, BGWidth / 10, BGWidth / 10)];
                btn.tag = 20 + i;
                //            btn.backgroundColor = [UIColor blackColor];
                [btn setImage:[UIImage imageNamed:@"icon_financial"] forState:UIControlStateNormal];
                btn.clipsToBounds = YES;
                btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
                btn.layer.cornerRadius = BGWidth / 16;
                [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
                [a addSubview:btn];
                [btn setContentMode:UIViewContentModeScaleToFill];
                UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(5 * BGWidth / 16, btn.bottom, BGWidth / 10,  10)];
                lab.text = @"金融";
                lab.font = [UIFont systemFontOfSize:font];
                lab.textAlignment = NSTextAlignmentCenter;
                [a addSubview:lab];
                
            } else if (i == 3) {
                
                UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(9 * BGWidth / 16, BGWidth / 10 + 16 + BGWidth /16 + BGWidth /10 + BGWidth /16 + 6, BGWidth / 10, BGWidth / 10)];
                btn.tag = 20 + i;
                //            btn.backgroundColor = [UIColor blackColor];
                [btn setImage:[UIImage imageNamed:@"icon_paper"] forState:UIControlStateNormal];
                btn.clipsToBounds = YES;
                btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
                btn.layer.cornerRadius = BGWidth / 16;
                [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
                [a addSubview:btn];
                [btn setContentMode:UIViewContentModeScaleToFill];
                UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(9 * BGWidth / 16, btn.bottom, BGWidth / 10, 10)];
                lab.text = @"票据";
                lab.font = [UIFont systemFontOfSize:font];
                lab.textAlignment = NSTextAlignmentCenter;
                [a addSubview:lab];
                
            } else if (i == 4) {
                
                UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(13 * BGWidth / 16, BGWidth / 10 + 16 + BGWidth /16 + BGWidth /10 + BGWidth /16 + 6, BGWidth / 10, BGWidth / 10)];
                btn.tag = 20 + i;
                //            btn.backgroundColor = [UIColor blackColor];
                [btn setImage:[UIImage imageNamed:@"icon_Credit reporting"] forState:UIControlStateNormal];
                btn.clipsToBounds = YES;
                btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
                btn.layer.cornerRadius = BGWidth / 16;
                [btn addTarget:self action:@selector(tiaozhuan:) forControlEvents:UIControlEventTouchUpInside];
                [a addSubview:btn];
                [btn setContentMode:UIViewContentModeScaleToFill];
                UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(13 * BGWidth / 16, btn.bottom, BGWidth / 10,  10)];
                lab.text = @"征信";
                lab.font = [UIFont systemFontOfSize:font];
                lab.textAlignment = NSTextAlignmentCenter;
                
                [a addSubview:lab];
                
            }
            
        }
    
    return a;
    } else {
        UIView *b = [[UIView alloc] init];
        return b;
    }
    
}

#pragma 公告信息页面的跳转
- (void)tiaozhuan:(UIButton *)btn {
    
    BGEntrustViewController *entrust = [[BGEntrustViewController alloc] init];
    BGFaBuViewController *fabushangpin = [[BGFaBuViewController alloc] init];
    BGAddInviteOneTableViewController *tender = [[BGAddInviteOneTableViewController alloc] init];
    BGAdvertisingController *adevertising = [[BGAdvertisingController alloc] init];
    BGPublicAnnoucementViewController * publicAnnoucement = [[BGPublicAnnoucementViewController alloc] init];
    tender.title = @"发布招标";
    
    switch (btn.tag) {
        case 11:
            self.hidesBottomBarWhenPushed = YES;
//            entrust.controllerType = @"home";
            [self.navigationController pushViewController:adevertising animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            break;
        case 12:
            self.hidesBottomBarWhenPushed = YES;
            entrust.controllerType = @"home";
            [self.navigationController pushViewController:entrust animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            break;
        case 13:
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:fabushangpin animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            break;
        case 14:
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:tender animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            break;
        case 31:
            self.hidesBottomBarWhenPushed = YES;
            publicAnnoucement.titleStr = @"热门资讯";
            publicAnnoucement.cateStr = @"zuixindongtai";
            [self.navigationController pushViewController:publicAnnoucement animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            break;
        case 32:
//            [self showMessage];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:[BGHomeWebViewController new] animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            break;
        case 33:
        {
            BGBrandZoneViewController *a = [[BGBrandZoneViewController alloc] init];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:a animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        }
            break;
        case 34:
            self.hidesBottomBarWhenPushed = YES;
            publicAnnoucement.titleStr = @"慧煤帮助";
            publicAnnoucement.cateStr = @"help";
            [self.navigationController pushViewController:publicAnnoucement animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            break;
        default:
            break;
    }
    
}

-(void)pageChanged:(UIPageControl *)page{
    // GWLog(@"%ld", page.currentPage);
    //根据页数，调整滚动视图
    CGFloat x = page.currentPage * _scrollView.bounds.size.width;
        [_scrollView setContentOffset:CGPointMake(x, 0) animated:YES];

}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isEqual: self.tableView]) {
        if (self.tableView.contentOffset.y > _scrollView.height) {
            // 上滑
            a.alpha = 0;
            
        }
        else{
            // 下滑
            a.alpha=1;
        }
    }
    
    if (_scrollView.contentOffset.x == 0){
        
        //当滚动到第一张的时候。滚到倒数第二张
        
        _scrollView.contentOffset = CGPointMake((_iamgeArrM.count - 2)*_scrollView.frame.size.width, 0);
        
    } else if (_scrollView.contentOffset.x == _scrollView.frame.size.width * (_iamgeArrM.count - 1)){
        
        //当滚动到最后一张时。滚到第二张
        
        _scrollView.contentOffset = CGPointMake(_scrollView.frame.size.width, 0);
        
    }
}
- (void)showMessage {
    
    UIAlertController *alerCro = [UIAlertController alertControllerWithTitle:@"提示" message:@"该功能尚未开发" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *lab = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];

    [alerCro addAction:lab];
    [self presentViewController:alerCro animated:YES completion:^{
        
    }];
    
}
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"netWorkStatus" object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}
//- (void)viewWillAppear:(BOOL)animated {
//    
//    view.hidden = NO;
//    
//}
//- (void)viewWillDisappear:(BOOL)animated {
//    
//    view.hidden = YES;
//    
//}
@end
